using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SpoilsDataSet;

namespace DataExtractor
{
    public partial class Form1 : Form
    {

        private const int OPEN_BETA = 0;
        private const int FIRST_EDITION = 1;
        private const int FIRST_EDITION_PART_2 = 2;
        private const int SEED_COTL = 3;
        private const int STAPLE_RESOURCE = 999;

        private LocalData LocalDataSet;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LocalDataSet = new LocalData();
        }

        private void RefreshCardData()
        {

            //Clear out table before filling it.
            LocalDataSet.CardData.Clear();

            //RefreshFromExcel("C:\\Users\\Rick\\Desktop\\openbetaspoiler.xls", OPEN_BETA);
            RefreshFromExcel(System.IO.Path.Combine(Application.StartupPath,"openbeta.xls"), OPEN_BETA);
            RefreshFromURL("http://www.thespoils.com/spoils/spoilers/FirstEditionSpoiler.html", FIRST_EDITION);
            RefreshFromURL("http://www.thespoils.com/spoils/spoilers/FirstEditionPart2Spoiler.html", FIRST_EDITION_PART_2);
            RefreshFromURL("http://www.thespoils.com/spoils/spoilers/SeedSpoiler.html", SEED_COTL);


            SpoilsDataSet.Helper.LoadEditions(LocalDataSet.Editions);


            BuildCards();





        }

        private void BuildCards()
        {
            DataView aDataView = LocalDataSet.CardData.DefaultView;
            aDataView.Sort = "Edition, Trade, Name";


            int aEdition = 0;
            int aOffset = 0;

            LocalDataSet.Card.Clear();

            for (int i = 0; i < aDataView.Count; i++)
            {
                LocalData.CardDataRow aCardDataRow = (LocalData.CardDataRow)aDataView[i].Row;
                if (aCardDataRow.Edition != aEdition)
                    aOffset = i;

                aEdition = aCardDataRow.Edition;
                string[] aTypeParts = aCardDataRow.Type.Split("-".ToCharArray(), 2);
                string aType = aTypeParts[0].Trim();
                string aSubType = "";
                if (aTypeParts.Length > 1)
                {
                    aSubType = aTypeParts[1].Trim();
                }



                LocalData.CardRow aCardRow = LocalDataSet.Card.AddCardRow(LocalDataSet.Editions.FindByNumber(aCardDataRow.Edition), i + 1 - aOffset, aCardDataRow.Trade, aCardDataRow.Name, aCardDataRow.Rarity, aCardDataRow.Cost, aCardDataRow.Threshold, aCardDataRow.ThresholdType, aType, aSubType, aCardDataRow.Strength, aCardDataRow.Life, aCardDataRow.Speed, aCardDataRow.CardText);

            }

            LocalDataSet.Card.AddCardRow(LocalDataSet.Editions.FindByNumber(999), 0, "", "The Tournament Faction", "Common", 0, 0, "", "Faction", "", -1, -1, -1, "");
            LocalDataSet.Card.AddCardRow(LocalDataSet.Editions.FindByNumber(999), 1, "Arcanist", "Obsession", "Common", 0, 0, "Obsession", "Resource", "", -1, -1, -1, "");
            LocalDataSet.Card.AddCardRow(LocalDataSet.Editions.FindByNumber(999), 2, "Banker", "Greed", "Common", 0, 0, "Greed", "Resource", "", -1, -1, -1, "");
            LocalDataSet.Card.AddCardRow(LocalDataSet.Editions.FindByNumber(999), 3, "Gearsmith", "Elitism", "Common", 0, 0, "Elitism", "Resource", "", -1, -1, -1, "");
            LocalDataSet.Card.AddCardRow(LocalDataSet.Editions.FindByNumber(999), 4, "Rogue", "Deception", "Common", 0, 0, "Deception", "Resource", "", -1, -1, -1, "");
            LocalDataSet.Card.AddCardRow(LocalDataSet.Editions.FindByNumber(999), 5, "Warlord", "Rage", "Common", 0, 0, "Rage", "Resource", "", -1, -1, -1, "");

        }



        private void RefreshFromExcel(string fileName, int edition)
        {
            System.Data.OleDb.OleDbConnection mExcelConnection = new System.Data.OleDb.OleDbConnection(
               "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=Excel 8.0;");

            mExcelConnection.Open();

            System.Data.OleDb.OleDbDataAdapter aAdapter = new System.Data.OleDb.OleDbDataAdapter("Select * from [openbeta$]", mExcelConnection);
            DataTable aDataTable = new DataTable();
            aAdapter.Fill(aDataTable);

            for (int i = 0; i < aDataTable.Rows.Count; i++)
            {


                DataRow aRow = aDataTable.Rows[i];


                    String aName = aRow["Name"].ToString();

                    if(string.IsNullOrEmpty(aName))
                        continue;

                    String aRarity = aRow["Rarity"].ToString();//.Substring(0, 1).ToUpper() + aRow["Rarity"].ToString().Substring(1).ToLower();
                    int aCost = -1;
                    if (!(aRow["Cost"] == null || aRow["Cost"].ToString() == ""))
                        aCost = (int)Math.Round((double)aRow["Cost"], 0);
                    int aThreshold = aRow["Threshold"].ToString().Length;

                    //string[] aTradeTypeInfo = aRow["TRADE,TYPE,SUBTYPE"].ToString().Split(" ".ToCharArray(), 2);
                    String aTrade = aRow["Trade"].ToString();
                    String aType = aRow["Type"].ToString(); ;

                    String aThresholdType = aRow["ThresholdType"].ToString(); ;

                    //switch (aTrade)
                    //{
                    //    case "Arcanist":
                    //        aThresholdType = "Obsession";
                    //        break;
                    //    case "Banker":
                    //        aThresholdType = "Greed";
                    //        break;
                    //    case "Gearsmith":
                    //        aThresholdType = "Elitism";
                    //        break;
                    //    case "Rogue":
                    //        aThresholdType = "Deception";
                    //        break;
                    //    case "Warlord":
                    //        aThresholdType = "Rage";
                    //        break;
                    //}

                    int aStrength = -1;
                    if (!(aRow["Strength"] == null || aRow["Strength"].ToString() == ""))
                        aStrength = (int)Math.Round((double)aRow["Strength"], 0);
                    int aLife = -1;
                    if (!(aRow["Life"] == null || aRow["Life"].ToString() == ""))
                        aLife = (int)Math.Round((double)aRow["Life"], 0);
                    int aSpeed = -1;
                    if (!(aRow["Speed"] == null || aRow["Speed"].ToString() == ""))
                        aSpeed = (int)Math.Round((double)aRow["Speed"], 0);
                    
                    //if (!(aRow["STRUC"] == null || aRow["STRUC"].ToString() == ""))
                    //    aStructure = (int)Math.Round((double)aRow["STRUC"], 0);

                    //if (aLife == -1 && aStructure != -1)
                    //    aLife = aStructure;

                    String aCardText = aRow["CardText"].ToString();

                    LocalData.CardDataRow aCardRow = LocalDataSet.CardData.AddCardDataRow(edition, aTrade, aName, aRarity, aCost, aThreshold, aThresholdType, aType, aStrength, aLife, aSpeed, aCardText);
            }

        }

        private void RefreshFromURL(string url, int edition)
        {
            StringBuilder aCardPage = new StringBuilder();
            String[] aCardInfo;

            string aNewLineChar = "\n";

            System.Net.HttpWebRequest aRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            byte[] aBuffer = new byte[8092];

            System.IO.Stream aResponseStream = ((System.Net.HttpWebResponse)(aRequest.GetResponse())).GetResponseStream();

            int aCount = 0;
            do
            {
                aCount = aResponseStream.Read(aBuffer, 0, aBuffer.Length);
                // make sure we read some data
                if (aCount != 0)
                {
                    // translate from bytes to ASCII text
                    aCardPage.Append(Encoding.ASCII.GetString(aBuffer, 0, aCount));
                }
            }
            while (aCount > 0); // any more data to read?

            aCardInfo = System.Text.RegularExpressions.Regex.Split(aCardPage.ToString(), "<hr>");

            for (int i = 1; i < aCardInfo.Length; i++)
            {
                int aFirstPos = 0;
                int aSecondPos = 0;

                aFirstPos = aCardInfo[i].IndexOf("<b>");
                if (aFirstPos > -1)
                {
                    aSecondPos = aCardInfo[i].IndexOf("</b>", aFirstPos);
                    String aName = aCardInfo[i].Substring(aFirstPos + 3, aSecondPos - aFirstPos - 3);

                    aFirstPos = aCardInfo[i].IndexOf(aNewLineChar, aSecondPos);
                    aSecondPos = aCardInfo[i].IndexOf("<br>", aFirstPos);
                    String aRarity = aCardInfo[i].Substring(aFirstPos + aNewLineChar.Length, aSecondPos - aFirstPos - aNewLineChar.Length);

                    aFirstPos = aCardInfo[i].IndexOf(aNewLineChar, aSecondPos);
                    aSecondPos = aFirstPos + 3;
                    int aCost = 0; //Mostly this will fail for double-thresh resource cards.
                    int.TryParse(aCardInfo[i].Substring(aFirstPos + aNewLineChar.Length, 3).Trim(),out aCost);

                    aFirstPos = aSecondPos;
                    aSecondPos = aCardInfo[i].IndexOf(aNewLineChar, aFirstPos);

                    System.Text.RegularExpressions.MatchCollection aMatches = System.Text.RegularExpressions.Regex.Matches(aCardInfo[i].Substring(aFirstPos, aSecondPos - aFirstPos), "/*.jpg");
                    int aThreshold = aMatches.Count;

                    aSecondPos = aCardInfo[i].IndexOf(".jpg");
                    aFirstPos = aCardInfo[i].Substring(0, aSecondPos).LastIndexOf("/");
                    String aThresholdType = aCardInfo[i].Substring(aFirstPos + 1, aSecondPos - aFirstPos - 1);
                    aThresholdType = aThresholdType[0].ToString().ToUpper() + aThresholdType.Substring(1);


                    aFirstPos = aCardInfo[i].IndexOf(aNewLineChar, aSecondPos);
                    aSecondPos = aCardInfo[i].IndexOf("<br>", aFirstPos);
                    String aType = aCardInfo[i].Substring(aFirstPos + aNewLineChar.Length, aSecondPos - aFirstPos - aNewLineChar.Length);


                    String aTrade = "";
                    switch (aThresholdType)
                    {
                        case "Obsession":
                            aTrade = "Arcanist";
                            break;
                        case "Greed":
                            aTrade = "Banker";
                            break;
                        case "Elitism":
                            aTrade = "Gearsmith";
                            break;
                        case "Deception":
                            aTrade = "Rogue";
                            break;
                        case "Rage":
                            aTrade = "Warlord";
                            break;
                    }

                    int aStrength = -1;
                    int aLife = -1;
                    int aSpeed = -1;

                    if (aType.StartsWith("Character", StringComparison.OrdinalIgnoreCase))
                    {
                        aFirstPos = aCardInfo[i].IndexOf(aNewLineChar, aSecondPos);
                        aSecondPos = aCardInfo[i].IndexOf("<br>", aFirstPos);

                        String[] aStats = System.Text.RegularExpressions.Regex.Split(aCardInfo[i].Substring(aFirstPos + aNewLineChar.Length, aSecondPos - aFirstPos - aNewLineChar.Length), "/");
                        aStrength = Convert.ToInt32(aStats[0]);
                        aLife = Convert.ToInt32(aStats[1]);
                        aSpeed = Convert.ToInt32(aStats[2]);

                    }

                    if (aType.StartsWith("Location"))
                    {
                        aFirstPos = aCardInfo[i].IndexOf(aNewLineChar, aSecondPos);
                        aSecondPos = aCardInfo[i].IndexOf("<br>", aFirstPos);

                        aLife = Convert.ToInt32(aCardInfo[i].Substring(aFirstPos + aNewLineChar.Length, aSecondPos - aFirstPos - aNewLineChar.Length).Replace("Structure:", "").Trim());
                    }

                    aFirstPos = aCardInfo[i].IndexOf(aNewLineChar + "<br>" + aNewLineChar, aSecondPos);
                    String aCardText = aCardInfo[i].Substring(aFirstPos + aNewLineChar.Length + 5 );
                    aCardText = aCardText.Replace("<br>", aNewLineChar);



                    LocalData.CardDataRow aCardRow = LocalDataSet.CardData.AddCardDataRow(edition, aTrade, aName, aRarity, aCost, aThreshold, aThresholdType, aType, aStrength, aLife, aSpeed, aCardText);


                }


            }

        }

        private void RefreshDataButton_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog aFileDialog = new FolderBrowserDialog();
            //aFileDialog.RootFolder = System.IO.Path.Combine(Application.StartupPath, "../../../SpoilsDB/bin/Debug/Data");
            if (aFileDialog.ShowDialog() == DialogResult.OK)
            {
                RefreshCardData();
                LocalDataSet.WriteXml(System.IO.Path.Combine(aFileDialog.SelectedPath, "CardData.xml"), XmlWriteMode.WriteSchema);
                this.Close();
            }


        }
    }
}